package managedbean.staff;

import entity.UserAccessRightsEntity;
import exception.ExistException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import managedbean.PageRedirectorBean;
import org.primefaces.model.MenuModel;
import session.stateless.StaffAccountSessionBean;
import session.stateless.SystemMessagesBean;
import util.entityhelper.StaffAccountState;
import util.enumeration.Country;
import util.enumeration.Department;
import util.enumeration.Gender;
import util.enumeration.JobPosition;
import util.generator.StaffMenuGenerator;
import util.localization.WebLocalization;

/**
 *
 * @author Swee Zhi
 */
@ManagedBean
@RequestScoped
public class StaffEditAccountManagedBean implements Serializable {
    @EJB
    private StaffAccountSessionBean staffAccountMgr;
    // EXCEPTION
    @EJB
    private SystemMessagesBean systemMessages;
    
    // use entity helpers to extract data (attribute extraction and formatting instead of entity in this open bean)
    private StaffAccountState staffAcctState;
    
    // fields for this bean
    private FacesContext ctx = FacesContext.getCurrentInstance();
    private WebLocalization localization;
    private PageRedirectorBean redirect;
    
    // fields passed from session
    private Long staffAccountId;
    private String preferredLocale;
    
    // other fields from database (+ display)
    private String username;
    private String currentPassword;
    private String lastname;
    private String firstname;
    private String gender;
    private String birthdate;
    private Country country;
    private String language;
    private String email;
    private String emailSecondary;
    private String department;
    private String jobPosition;
    private String joinDate;
    private Date passwordChangeDate;
    private List<String> accessRightsList;
    
    // display only
    private String name;
    private String newPassword;
    private String confirmPassword;
    private MenuModel staffMenuModel;
    
    
    public StaffEditAccountManagedBean() {
        /* LOCALIZATION */
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        /* END LOCALIZATION */
        
        /* pre-load values from session and database */
        // get account ID values from session
        if (ctx.getExternalContext().getSessionMap().containsKey("staffAccountId")) {
            staffAccountId = (Long) ctx.getExternalContext().getSessionMap().get("staffAccountId");
            // put back the session IDs taken
            ctx.getExternalContext().getSessionMap().put("staffAccountId", staffAccountId);
        }
        else {
            // redirect back to login
            redirect = new PageRedirectorBean();
            redirect.goStaffLoginPageAtPreviousLevel();
        }
        /* END load values from session and database */    
    }
    
    public void initView(PhaseEvent event) {
        /* LOCALIZATION */
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        /* END LOCALIZATION */
        
        try {
            // set language for all MANAGERS for all THROWABLE EXCEPTIONS in backend
            // to use this line everytime possible language changes
            staffAccountMgr.setSelectedLocale(preferredLocale);
            // get data from backend, exception alrd thrown by backend if these methods fail.
            
            staffAcctState = staffAccountMgr.getStaffAccountByID(staffAccountId);
            
            username = staffAcctState.getUsername();
            
            lastname = staffAcctState.getStaff().getLastName();
            firstname = staffAcctState.getStaff().getFirstName();
            name = lastname + " " + firstname;
            
            Gender savedGender = staffAcctState.getStaff().getGender();
            gender = localization.getLocalizedGender(savedGender);
            
            Date savedBirthdate = staffAcctState.getStaff().getBirthdate();
            birthdate = localization.getLocalizedDateFormat(savedBirthdate);
            
            Country savedCountry = staffAcctState.getStaff().getCountry();
            if (country == null) {
                country = savedCountry;
            }
            
            String savedLocale = staffAcctState.getStaff().getLocale();
            if (language == null) {
                language = savedLocale;
            }
            
            email = staffAcctState.getStaff().getEmail();
                    
            if (emailSecondary == null) {
                emailSecondary = staffAcctState.getStaff().getEmailSecondary();
            }
            
            Department savedDepartment = staffAcctState.getStaff().getDepartment();
            if (department == null) {
                department = localization.getLocalizedDepartment(savedDepartment);
            }

            JobPosition savedJobPosition = staffAcctState.getStaff().getJobPosition();
            if (jobPosition == null) {
                jobPosition = localization.getLocalizedJobPosition(savedJobPosition);
            }

            Date savedJoinDate = staffAcctState.getStaff().getJoinDate();
            if (jobPosition == null) {
                joinDate = localization.getLocalizedDateFormat(savedJoinDate);
            }

            passwordChangeDate = staffAcctState.getPasswordChangeDate();

            List<UserAccessRightsEntity> savedList = new ArrayList();
            savedList = staffAcctState.getAccessRights();
            accessRightsList = new ArrayList();
            // convert from entity to enum
            for (int i=0; i < savedList.size(); i++) {
                String localizedAccessRight = localization.getLocalizedAccessRight(savedList.get(i).getAccessRight());
                accessRightsList.add(localizedAccessRight);
            }

            // menu
            StaffMenuGenerator menuGenerator = new StaffMenuGenerator(staffAcctState);
            staffMenuModel = menuGenerator.generateStaffMenu();
        }
        catch (ExistException ex) {
//            System.out.println(ex.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
        }
        catch (Exception ex) {
            ex.printStackTrace();
//            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
        }
    }
    
    public void updateStaffDetails(ActionEvent event) {
        /* LOCALIZATION */
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        /* END LOCALIZATION */
        
        boolean passwordCheckOK = false;
        boolean hasNewUpdate = false;
        boolean passwordChecking = false;
        String statusMessage = "";
        
        try {
            // set language for all MANAGERS for all THROWABLE EXCEPTIONS in backend
            // to use this line everytime possible language changes
            staffAccountMgr.setSelectedLocale(preferredLocale);

            // TODO: if can reach til this page it means account ID exists.. can set error for further safety message when free
            staffAcctState = staffAccountMgr.getStaffAccountByID(staffAccountId);

            /* do all necessary checks and set values before UPDATE */
            // check password fields if edited..set back to current password if nothing..
            String latestPassword = staffAcctState.getPassword();
            if (currentPassword.isEmpty()) {
                passwordChecking = true;
                
                if (!newPassword.isEmpty()) {
                    statusMessage = systemMessages.getSystemMessage("CURRENT_PASSWORD_REQUIRED", preferredLocale);
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, statusMessage, ""));
                    passwordCheckOK = false;
                }
            }
            else {
                passwordChecking = true;
                if (newPassword.isEmpty()) {
                    statusMessage = systemMessages.getSystemMessage("NEW_PASSWORD_REQUIRED", preferredLocale);
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, statusMessage, ""));
                    passwordCheckOK = false;
                }
                else {
                    if (currentPassword.equals(staffAcctState.getPassword())) {
                        latestPassword = newPassword;
                        passwordCheckOK = true;
                    }
                    else {
                        statusMessage = systemMessages.getSystemMessage("CURRENT_PASSWORD_INCORRECT", preferredLocale);
                        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, statusMessage, ""));
                        passwordCheckOK = false;
                    }
                }
            }
            
            if (passwordCheckOK == true) {
                hasNewUpdate = true;
            }
            
            // language just retrieve as it is because it is dropdown list
            if (language.equals(staffAcctState.getStaff().getLocale())) {
                // no change
                language = staffAcctState.getStaff().getLocale();
            }
            else {
                hasNewUpdate = true;
            }
            
            // country just retrieve as it is because it is dropdown list
            if (country.equals(staffAcctState.getStaff().getCountry())) {
                // no change
                country = staffAcctState.getStaff().getCountry();
            }
            else {
                hasNewUpdate = true;
            }
            
            // emailSecondary just retrieve as it is because if as it is means user no change else del on purpose
            if (emailSecondary.equals(staffAcctState.getStaff().getEmailSecondary())) {
                // no change
                emailSecondary = staffAcctState.getStaff().getEmailSecondary();
            }
            else {
                hasNewUpdate = true;
            }
            
            if (hasNewUpdate == true) {
                // update
                staffAccountMgr.updateStaffAccount(staffAccountId, latestPassword);
                staffAccountMgr.updateStaff(staffAcctState.getStaff().getId(), country, language, emailSecondary);
                statusMessage = systemMessages.getSystemMessage("UPDATE_SUCCESS", preferredLocale);
//                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, statusMessage, ""));
                // send status message to next page
                ctx.getExternalContext().getSessionMap().put("statusMessageFromEdit", statusMessage);
                
                ctx.getExternalContext().getSessionMap().put("savedLocale", language);
                reset();
                redirect = new PageRedirectorBean();
                redirect.goStaffWelcomePage();
            }
            else {
                if (passwordChecking == false) {
                    statusMessage = systemMessages.getSystemMessage("UPDATE_NO_CHANGES", preferredLocale);
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, statusMessage, ""));
                }
            }
        }
        catch (ExistException ex) {
//            System.out.println(ex.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
        }
        catch (Exception ex) {
            ex.printStackTrace();
//            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
        }
    }

    private void reset() {
        currentPassword = "";
        newPassword = "";
        confirmPassword = "";
    }

    public StaffAccountSessionBean getStaffAccountMgr() {
        return staffAccountMgr;
    }

    public void setStaffAccountMgr(StaffAccountSessionBean staffAccountMgr) {
        this.staffAccountMgr = staffAccountMgr;
    }

    public FacesContext getCtx() {
        return ctx;
    }

    public void setCtx(FacesContext ctx) {
        this.ctx = ctx;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public SystemMessagesBean getSystemMessages() {
        return systemMessages;
    }

    public void setSystemMessages(SystemMessagesBean systemMessages) {
        this.systemMessages = systemMessages;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPreferredLocale() {
        return preferredLocale;
    }

    public void setPreferredLocale(String preferredLocale) {
        this.preferredLocale = preferredLocale;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getEmailSecondary() {
        return emailSecondary;
    }

    public void setEmailSecondary(String emailSecondary) {
        this.emailSecondary = emailSecondary;
    }

    public Long getStaffAccountId() {
        return staffAccountId;
    }

    public void setStaffAccountId(Long staffAccountId) {
        this.staffAccountId = staffAccountId;
    }

    public StaffAccountState getStaffAcctState() {
        return staffAcctState;
    }

    public void setStaffAcctState(StaffAccountState staffAcctState) {
        this.staffAcctState = staffAcctState;
    }

    public WebLocalization getLocalization() {
        return localization;
    }

    public void setLocalization(WebLocalization localization) {
        this.localization = localization;
    }

    public String getConfirmPassword() {
        return confirmPassword;
    }

    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }

    public String getNewPassword() {
        return newPassword;
    }

    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }

    public Country getCountry() {
        return country;
    }

    public void setCountry(Country country) {
        this.country = country;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getBirthdate() {
        return birthdate;
    }

    public void setBirthdate(String birthdate) {
        this.birthdate = birthdate;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    public String getCurrentPassword() {
        return currentPassword;
    }

    public void setCurrentPassword(String currentPassword) {
        this.currentPassword = currentPassword;
    }

    public PageRedirectorBean getRedirect() {
        return redirect;
    }

    public void setRedirect(PageRedirectorBean redirect) {
        this.redirect = redirect;
    }

    public MenuModel getStaffMenuModel() {
        return staffMenuModel;
    }

    public void setStaffMenuModel(MenuModel staffMenuModel) {
        this.staffMenuModel = staffMenuModel;
    }

    public List<String> getAccessRightsList() {
        return accessRightsList;
    }

    public void setAccessRightsList(List<String> accessRightsList) {
        this.accessRightsList = accessRightsList;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getJobPosition() {
        return jobPosition;
    }

    public void setJobPosition(String jobPosition) {
        this.jobPosition = jobPosition;
    }

    public String getJoinDate() {
        return joinDate;
    }

    public void setJoinDate(String joinDate) {
        this.joinDate = joinDate;
    }

    public Date getPasswordChangeDate() {
        return passwordChangeDate;
    }

    public void setPasswordChangeDate(Date passwordChangeDate) {
        this.passwordChangeDate = passwordChangeDate;
    }
}